<template>
  <div style="margin-inside: 20px">
    <div id="container" style="height: 30vh;margin-outside: 20px" />
  </div>
  <van-cell-group>
    <van-cell title="经纬度" :value="`经度: ${pointLng} \n 纬度: ${pointLat}`"/>
    <van-cell title="地址" :value="nowAddress"/>
  </van-cell-group>
  <van-button style="margin-top: 20px" type="primary" block @click="doSearchNearby(pointLng,pointLat)">查找附近的人</van-button>
</template>

<script setup lang="ts">

import {onMounted, onUnmounted, ref} from "vue";
import {useRoute, useRouter} from "vue-router";
import AMapLoader from "@amap/amap-jsapi-loader";
import {showFailToast} from "vant";
const route = useRoute();

//@ts-ignore
window._AMapSecurityConfig = {
  securityJsCode: "d8fa2f8a8ef511c2d860b6fd783236b7",
};

let map = null;

const pointLng = ref();
const pointLat = ref();
const nowAddress = ref();

onMounted(() => {
  AMapLoader.load({
    key: "0ed813a9c6d3aa0e19e21564ba80ec45", //申请好的Web端开发者key，调用 load 时必填
    version: "2.0", //指定要加载的 JS API 的版本，缺省时默认为 1.4.15
    plugins: ["AMap.Geolocation", "AMap.Geocoder"],
  })
      .then((AMap) => {
        //JS API 加载完成后获取AMap对象
        const map = new AMap.Map('container', {
          viewMode: "2D",
          zoom: 10,
          resizeEnable: true,
        });
        AMap.plugin('AMap.Geolocation', function () {
          const geolocation = new AMap.Geolocation({
            enableHighAccuracy: true, // 是否使用高精度定位，默认：true
            timeout: 10000, // 设置定位超时时间，默认：无穷大
            buttonPosition: 'RB', // 定位按钮的停靠位置
            offset: new AMap.Pixel(10, 20),  // 定位按钮的停靠位置的偏移量
            zoomToAccuracy: true,  //  定位成功后调整地图视野范围使定位位置及精度范围视野内可见，默认：false
            convert: true,
          })
          map.addControl(geolocation);
          geolocation.getCurrentPosition(<PositionCallback>function (status, result) {
            if (status == 'complete') {
              onComplete(result)
            } else {
              onError(result)
            }
          });

          function onComplete(data) {
            console.log("data.position.lng:" + data.position.lng);
            console.log("data.position.lat:" + data.position.lat);
            // data是具体的定位信息
            pointLng.value = data.position.lng;
            pointLat.value = data.position.lat;
            AMap.plugin('AMap.Geocoder', function () {
              AMap.plugin('AMap.Geocoder', function () {
                const geocoder = new AMap.Geocoder({
                  city: '郑州', // city指定进行编码查询的城市，支持传入城市名、adcode和citycode
                })
                const lnglat = [data.position.lng, data.position.lat];

                geocoder.getAddress(lnglat, function (status, result) {
                  if (status === 'complete' && result.info === 'OK') {
                    nowAddress.value = result.regeocode.formattedAddress;
                  } else {
                    showFailToast("定位失败");
                  }
                })
              })
            })
            //调用后端接口
          }

          function onError(data) {
            // 定位出错
            showFailToast("定位失败");
          }
        })
      })
      .catch((e) => {
        console.log(e);
      });
});

const router = useRouter();
const doSearchNearby = (pointLng: number,pointLat: number) => {
  router.push({
    path: '/user/list/nearby',
    query: {
      pointLng,
      pointLat
    }
  })
};

onUnmounted(()=>{
  map?.destroy();
})

</script>

<style scoped>
#container {
  padding: 0px;
  margin: 0px;
  width: 100%;
  height: 800px;
}
</style>